let { verifyToken } = require('../utils/tokenUtil');

module.exports = function(req, res, next) {

    // 单独处理预检请求
    if (req.method === 'OPTIONS') {
        next();
        return;
    }

    let token = req.headers.token;
    // 判断req的headers中是否含有有效的token
    if (token) {
        verifyToken(token).then(
            val => {
                next();
            }, rea => {
                // token非法或过期时
                res.statusCode = 401;
                res.json({
                    code: 2002,
                    message: rea.message
                });
            })
    } else {
        res.statusCode = 401;
        res.json({
            code: 2001,
            message: `抱歉，缺少token`
        });
    }
}